package com.googlecode.spruce.web.admin.host;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.googlecode.spruce.dao.HostDao;
import com.googlecode.spruce.dao.OperatingSystemDao;
import com.googlecode.spruce.domain.Host;
import com.googlecode.spruce.domain.OperatingSystem;

@Controller
@RequestMapping("/admin/host")
public class HostDashboard
{

    @Autowired
    private HostDao hostDao;

    @Autowired
    private OperatingSystemDao operatingSystemDao;

    @RequestMapping(value = "/index.html", method = RequestMethod.GET)
    public ModelAndView getAll()
    {
        final ModelAndView model = new ModelAndView("host/index");

        final List<OperatingSystem> operatingSystems = this.operatingSystemDao.getAll();
        final List<Host> hosts = this.hostDao.getAll();

        model.addObject("operatingSystems", operatingSystems);
        model.addObject("hosts", hosts);

        return model;
    }

    @RequestMapping(value = "/add.do", method = RequestMethod.POST)
    public ModelAndView add(@RequestParam("name") String name, @RequestParam("ipAddress") String ipAddress,
            @RequestParam("osid") Integer osID)
    {
        final OperatingSystem os = this.operatingSystemDao.findByID(osID);

        final Host host = new Host();

        host.setName(name);
        host.setIpAddress(ipAddress);
        host.setOperatingSystem(os);

        this.hostDao.save(host);

        return getAll();
    }
}
